package kr.re.etri.snsenabler.server;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import kr.re.etri.snsenabler.client.service.SnsEnablerService;
import kr.re.etri.snsenabler.shared.Data;
import kr.re.etri.snsenabler.shared.LoginProperties;
import kr.re.etri.snsenabler.shared.ServiceResponse;

public class SnsEnablerServlet extends AbstractServiceServlet implements SnsEnablerService {
	private Logger logger = Logger.getLogger(SnsEnablerServlet.class.getName());

	@Override
	public ServiceResponse getUser() {
		Object userObject = getThreadLocalRequest().getSession().getAttribute(Constants.USER);
		if (userObject == null || !(userObject instanceof Data)) {
			return new ServiceResponse(false);
		}

		return new ServiceResponse((Data)userObject);
	}

	@Override
	public ServiceResponse login(Data loginData) {
		String loginId = loginData.getString(LoginProperties.LOGIN_ID);
		String password = loginData.getString(LoginProperties.LOGIN_PASSWORD);

		ServiceResponse response = null;
		Data userData = getDbService().getUser(loginId);
		if (userData != null) {
			String savedPassword = userData.getString(LoginProperties.LOGIN_PASSWORD);
			if (password.equals(savedPassword)) {
				getThreadLocalRequest().getSession().setAttribute(Constants.USER, userData);
				response = new ServiceResponse(userData);
			} else {
				response = new ServiceResponse(false);
			}
		} else {
			try {
				getDbService().insertUser(loginData);
				getThreadLocalRequest().getSession().setAttribute(Constants.USER, userData);
				response = new ServiceResponse(loginData);
			} catch (Exception e) {
				logger.log(Level.SEVERE, e.getMessage(), e);
				response = new ServiceResponse(e.getMessage());
			}
		}
		return response;
	}

	@Override
	public ServiceResponse loadJoinedSocialServiceProviders(String loginId) {
		ArrayList<Data> providers = getDbService().getSocialServiceProviders(loginId);
		return new ServiceResponse(providers);
	}
}
